package cn.kailangtu.serialportv2;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

import cn.kailangtu.serialport.CommonUtils;

public class DataAnalysis {
    static String HEARD = "7B7B";
    static String END = "7D7D";
    public static List<String> GetCmd(String source){
        /*
        1,找7B7B,找不到，整条指令扔掉
        2，得到长度，校验长度：
            如果长度算出的结尾位置正确，算一条指令
            如果长度算出的结尾位置不正常，找下一个7B7B，如果没有，全扔掉。如果找到重复上一步的判断
        3，获取一条完整指令后，看后面是否有其他指令，有就把后面的截出来，返回上面1的步骤，继续判断
         */

        List<String> result = new ArrayList<>();
        source = source.toUpperCase();
        while(source.length() > 15)
        {
            int position7B7B = source.indexOf(HEARD);
            if(position7B7B > -1)
            {
                int positionLength = position7B7B + 6;
                int length  = new BigInteger( source.substring(positionLength,positionLength+4), 16).intValue();
                int positionEnd = length + 10 + position7B7B;
                int positionComplete = positionEnd + 6;
                String currentEnd = source.substring(positionEnd,positionEnd+4);
                if(currentEnd.equals(END))
                {
                    String foundCmd = source.substring(position7B7B,positionComplete);
                    if(CommonUtils.check(foundCmd)) {
                        result.add(foundCmd);
                    }
                    if(source.length() > positionComplete) {
                        source = source.substring(positionComplete);
                    }
                    else
                    {
                        source = "";
                    }
                }
            }else {
                source = "";
            }
        }
        return result;
    }
}
